package team.gl.nio.isnser;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

import java.util.Vector;

import com.richman.controller.DaShui;
import com.richman.hg.HGManager;

import team.gl.nio.cmn.Bag;
import team.gl.nio.cmn.ISNBag;

public class ISNNettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        //System.out.println("server channelRead..");
        ISNBag us = (ISNBag) msg;
        if(us.getReq().equals("isn")) {
        	
        	ISNBag bag = new ISNBag("isn");
        	bag.setSenddatas(DaShui.isnps38EventManager.getsenddatas());
        	//bag.setTeams(DaShui.mainWnd.getHGISNTeamsList());
        	bag.setHGEvents(HGManager.gethgevents());
        	ctx.channel().writeAndFlush(bag);

        }
    
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("server channelReadComplete..");
        ctx.flush();//ˢ�º�Ž���ݷ�����SocketChannel
    }
    

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        //System.out.println("server exceptionCaught.." + cause.getMessage());
        ctx.close();
    }
    
    
    
    
    // 心跳丢失计数器
    private int counter;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //System.out.println("--- Client is active ---");
    	

    	
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
       
    	String uuid = ctx.channel().id().asLongText();
   }



    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            // 空闲6s之后触发 (心跳包丢失)
            if (counter >= 3) {
                // 连续丢失3个心跳包 (断开连接)
                ctx.channel().close().sync();
                System.out.println("已与Client断开连接");
            } else {
                counter++;
                System.out.println("丢失了第 " + counter + " 个心跳包");
            }
        }
    }





}
